<%
            session.setAttribute("posting", page);
%>
<?php session_start();

    $_SESSION['page']='posting';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Posting</title>
    <link rel="stylesheet" type="text/css" title="T1" href="stylesheet/progin.css" id="link_theme" />
	<link rel="stylesheet" type="text/css" title="T1" href="stylesheet/posting.css" />
		<meta name="description" content="RERGag, Make You Laughing" />
		<meta name="keywords" content="laugh" />
		<meta name="author" content="Robertus Theodore" />
		<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    </head>
    <body>
        <?php include 'header.php';?>
		
        <div class="main_container">
            <div id="preview"></div>
	
	<div align="left" style="width: 500px;" >

	<form id="posting_form" name="posting_form" method="post" action="posting.php" onsubmit="checkOnSubmit()" enctype="multipart/form-data">
	<fieldset><legend>Posting Baru</legend>

	<label class="label_posting">Judul </label><input id="form_nama" class="input_posting" name="title" type="text"></input><br/>

	<label class="label_posting">Pilihan </label><input id="option_link" class="input_posting" type="radio" name="option" value="link" onclick="return link_enable()" />Link<br />
	<label class="label_posting"></label><input id="option_image" class="input_posting" type="radio" name="option" value="image"  onclick="return image_enable()"/>Image<br />
	<label class="label_posting"></label><input id="option_video" class="input_posting" type="radio" name="option" value="video" onclick="return video_enable()"/>Video<br />

	<label class="label_posting">Link</label><input class="input_posting" id="form_link" type="text" name="link_url" disabled ="disabled"  ></input><font id="linkValidator" class="validation"></font><br />
	<label class="label_posting">Deskripsi Link</label><textarea class="textarea_posting" id="form_link_description" name="link_description" rows="5" cols="25" disabled ="disabled"  ></textarea><br />

        <label class="label_posting">Image </label><input class="input_posting" name="gambar" type="file"  disabled ="disabled" /><br />

        <label class="label_posting">Video </label><input class="input_posting" id="form_video"  name="mov" type="text" disabled ="disabled"  /><br />

        <label class="label_posting">Tag </label><input class="input_posting" name="tag" type="text"/><br />

        <label class="label_posting">&nbsp;</label><input type="Submit" class="input_posting" value="Posting"/>
        <input type="button" name="buttonPreview" class="input_posting" onclick="preview()" value="Preview"/>

	</fieldset>

	</form>
        <%@ page language="java" import="java.sql.*" %>


        <?php
            $con = mysql_connect("localhost","root","");
            if (!$con)
            {
                die('Could not connect: ' . mysql_error());
            }

            mysql_select_db("progin_171_13509008", $con);


            // get User Name From session
            $userPosting = $_SESSION['user_name'];

            // get next id_content for image naming
            global $curIDContent;
            $qCount = mysql_query("SELECT MAX(id_content) FROM content");
            $results = mysql_fetch_array($qCount);
            $curIDContent = $results['MAX(id_content)'] + 1;

            //get form value
            $optionResult = $_POST[option];
            $titleContent = $_POST[title];
            $linkURL = $_POST[link_url];
            $linkDescription = $_POST[link_description];
            $videoContent = $_POST[mov];
            $tagContent = $_POST[tag];

            $boolPass = false; // boolean for last process

            if($optionResult == 'link'){
                if ($titleContent==""){
                        echo "Judul belum terisi.</br>";
                }
                if ($linkURL==""){
                    echo "Url link belum terisi.</br>";
                }
                if($linkDescription==""){
                    echo "Deskripsi Link belum terisi.</br>";
                }
                else {
                    // !! nanti user diambil dari session
                    $sqlInsertLinkContent = "INSERT INTO content (title, content_type, content_filled, content_description, posting_time, user_name) VALUES ('$titleContent', '$optionResult', '$linkURL' ,'$linkDescription', now(), '$userPosting')";
                    mysql_query($sqlInsertLinkContent) or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                    echo "Link Posted!";
                    $boolPass = true;
                }
           }
           if ($optionResult== 'image'){
                    if ($titleContent==""){
                        echo "Judul belum terisi.</br>";
                    }
                    //check file type
                    if ($_FILES["gambar"]["type"] != "image/jpeg"){
                        echo "File belum terisi, tipe File seharusnya jpg/jpeg";
                    }
                    else {                        
                        if(is_uploaded_file($_FILES['gambar']['tmp_name'])){
                            $fileNameImage = $curIDContent.".jpg"; //get the file name
                            $move = move_uploaded_file($_FILES['gambar']['tmp_name'], 'C://xampp/htdocs/rergag/images/posting/'.$fileNameImage); //save image to the folder
                            if ($move){echo "Posting berhasil!";}
                        }
                        $queryInsertImage = "INSERT INTO content (title, content_type, content_filled,content_description, posting_time, user_name) VALUES ('$titleContent', '$optionResult','images/posting/$fileNameImage', '', now(), '$userPosting')";
                        mysql_query($queryInsertImage) or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                        echo "Image Posted!";
                        $boolPass = true;
                }
           }
           // content_type = video
           if ($optionResult== 'video'){
                if ($titleContent==""){
                        echo "Judul belum terisi.</br>";
                }
                if ($videoContent==""){
                    echo "Video Url belum terisi.</br>";
                }
                else {
                    // !! nanti user diambil dari session
                    $sqlInsertVideoContent = "INSERT INTO content (title, content_type, content_filled, content_description, posting_time, user_name) VALUES ('$titleContent', '$optionResult', '$videoContent' ,'', now(), '$userPosting')";
                    mysql_query($sqlInsertVideoContent) or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                    echo "Video Posted!";
                    $boolPass = true;
                }
           }

           // check existing tag and insert new tag, tag_content
            if($boolPass == true){
                // parse tag content
                $data = array_filter(explode(',', $data));
                $tagArray = explode(',', $tagContent);

                // remove space
                $i=0;
                foreach ($tagArray as $v) {
                    $tagArray[$i]= trim($v);
                    $i++;
                }
                // return $tagArray as result for tag input, check on database

                //get current tag on database
                $result_check = mysql_query("select tag_name from tag");
                $currentTagOnDatabase = array();
                $j=0;   //counter
                while ($rowCheckTemp = mysql_fetch_array($result_check)){
                    $currentTagOnDatabase[$j]= $rowCheckTemp['tag_name'];
                    $j++;
                }

                // cross check data and insert tag
                $countCurDataTag=sizeof($currentTagOnDatabase);
                $countTagArray = sizeof($tagArray);

                $isExist = false;
                $j=0;
                $i=0;
                for ($j = 0 ; $j < $countTagArray; $j++){
                    for ($i=0; $i< $countCurDataTag; $i++){
                        if($tagArray[$j]== $currentTagOnDatabase[$i]){
                            // if we found same data on database, set element with undefined value
                            $tagArray[$j]='9999';
                        }
                    }
                }

                // $tagArray with value = 9999 is not valid
                for ($k= 0; $k < $countTagArray; $k++){
                // input tag valid, insert into database
                    if($tagArray[$k]!='9999' && $tagArray[$k]!=''){

                        $q1 = "INSERT INTO tag (tag_name) VALUES ('$tagArray[$k]')";
                        echo $q1;
                        mysql_query($q1) or DIE ("GAGAL MELAKUKAN QUERY. " . mysql_error());

                        //get id_tag which have just inserted
                        $q2 = "select id_tag from tag where tag_name =\"$tagArray[$k]\"";
                        $res = mysql_query($q2);
                        $idTagNew =0;
                        while ($ro = mysql_fetch_array($res)){
                            $idTagNew = $ro[id_tag];
                        }
                        //insert into tag relation with content
                        $q3 = "Insert Into tag_content(id_tag, id_content) VALUES( $idTagNew,$curIDContent)";
                        mysql_query($q3) or DIE ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                    }
                }
				
                // Check for achievement
                // get next id_content for image naming
                global $totalPosting;
                $qCountTotalPosting = mysql_query("select count(*)as totalPosting from content where user_name ='$userPosting'");
                while ($row1 = mysql_fetch_array($qCountTotalPosting)){
                    $totalPosting = $row1['totalPosting'];
                }
                if ($totalPosting =='1'){
                    //Insert Achievement ke user
                    mysql_query("Insert into user_achievement (user_name, id_achievement) VALUES ('$userPosting',1) ") or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                }
                if ($totalPosting =='10'){
                    mysql_query ("Insert into user_achievement (user_name, id_achievement) VALUES ('$userPosting',2) ") or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                }


                // testing session untuk detail
                //$_SESSION['user_name']='robert';

                //redirect to detil content
                $_SESSION['id_content']=$curIDContent;
                echo "<script>document.location.href='detail.php'</script>";
            }

            

        ?>
	</div>
        <script type="text/javascript" src="script/posting.js"></script>
        <script type="text/javascript" src="script/progin.js"></script>
        </div>
    </body>
</html>
